import numpy as np
import pandas as pd

from rectify.get_address_by_id import get_address_by_id


def dzty(df, search_column1, update_column1, search_column2):

    try:
        # 读取Excel文件
        df.replace(np.nan, "", inplace=True)  # 将NaN替换为None
        # 遍历每一行
        for index, row in df.iterrows():
            c1 = row[search_column1]  # 户籍
            c2 = row[update_column1]  # 居住地址
            c3 = row[search_column2]  # 身份证号

            # 使用split()方法按空格分割文本，并截取前五段
            segments = c2.split()

            # 确保分割后的段数量大于或等于五个
            if len(segments) >= 5:
                first_five_segments = segments[:5]
                result = ' '.join(first_five_segments)
            else:
                result = ' '.join(segments)

            # 输出结果
            print("前五段:", result)

            if "北京市" in c1:
                # 使用splitlines()方法按行分割文本，并统计分割后的段落数量
                segments = c1.split()
                print("户籍中填写的数量:", len(segments))
                if len(segments) < 5:
                    print(f"更新前的户籍地址: {df.at[index, search_column1]}")
                    df.at[index, search_column1] = result
                    print(f"更新后的户籍地址: {df.at[index, search_column1]}")
            else:
                file_path = '文档/身份证归属地查询表.xlsx'
                address_info = get_address_by_id(c3, file_path)
                print(f"身份证号: {c3}")
                print(f"省级行政区: {address_info['province']}")
                print(f"地级行政区: {address_info['city']}")
                print(f"县级行政区: {address_info['county']}")
                if address_info['province'] != "未知省":
                    if search_column1 != f"{address_info['province']} {address_info['city']} {address_info['county']}":
                        df.at[index, search_column1] = f"{address_info['province']} {address_info['city']} {address_info['county']}"
                        print(f"更新后的户籍地址: {df.at[index, search_column1]}")
        # 保存更新后的Excel文件
        print("[户籍地址]已完成处理。")
        return df
    except Exception as e:
        print(f"户籍地址处理时发生错误：{e}")
